﻿using FairyGUI;
using UnityEngine;
using ZFramework.Runtime;

namespace ZGame
{
    public abstract class FGuiUIFormLogicBase : UIFormLogic
    {
        public abstract string UIPackageName { get; }
        
        public abstract string UIComponentName { get; }

        public const int DepthFactor = 100;
        
        private UIPanel m_CachedUIPanel;
        
        public GComponent UI
        {
            get;
            private set;
        }
        
        public int Depth => m_CachedUIPanel.sortingOrder;

        private bool m_IsCreated = false;
        
        public void InitUIPanel(IUIGroup uiGroup, object userData)
        {
            if (m_IsCreated)
                return;
            m_IsCreated = true;
            transform.localPosition = Vector3.zero;
            m_CachedUIPanel = gameObject.GetOrAddComponent<UIPanel>();
            m_CachedUIPanel.packageName = UIPackageName;
            m_CachedUIPanel.componentName = UIComponentName;
            gameObject.SetLayerRecursively(Constant.Layer.UILayerId);
            UI = m_CachedUIPanel.ui;
            //屏幕适配
            m_CachedUIPanel.fitScreen = FGuiContentScaleHelper.GetFairyUIScaleType() == FairyUIScaleType.Width ? FitScreen.FitWidthAndSetMiddle : FitScreen.FitHeightAndSetCenter;
            //m_CachedUIPanel.fitScreen = FitScreen.FitSize;
            m_CachedUIPanel.ApplyModifiedProperties(false, true);
            GameEntry.fguiUIPackageMgr.AddUIPackageRefCount(UIPackageName);
        }
        
        public void DeInitUIPanel()
        {
            GameEntry.fguiUIPackageMgr.SubUIPackageRefCount(UIPackageName);
            UI.Dispose();
            UI = null;
        }
        
        public override void OnDepthChanged(int uiGroupDepth, int depthInUIGroup)
        {
            base.OnDepthChanged(uiGroupDepth, depthInUIGroup);
            m_CachedUIPanel.SetSortingOrder(DepthFactor * uiGroupDepth + DepthFactor * depthInUIGroup, true);
        }

        protected override void InternalSetVisible(bool visible)
        {
            base.InternalSetVisible(visible);
            UI.displayObject.visible = visible;
        }
    }
}